package com.mia.props.client.container;

import com.mia.props.common.entities.TileContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;

public class ContainerChestProps extends Container {
   private TileContainer tileEntity;
   private int invX;
   private int invY = 0;

   public ContainerChestProps(InventoryPlayer inventoryPlayer, TileEntity te) {
      this.tileEntity = (TileContainer)te;
      this.invX = this.tileEntity.getSizeInventoryX();
      this.invY = this.tileEntity.getSizeInventoryY();
      int widthSlots = this.invX * 18;
      int heightSlots = this.invY * 18;
      int leftMainInv = (180 - widthSlots) / 2;
      int leftHotbarInv = 9;
      this.tileEntity.openInventory();

      int y;
      int x;
      for(y = 0; y < this.invY; ++y) {
         for(x = 0; x < this.invX; ++x) {
            this.addSlotToContainer(new Slot(this.tileEntity, x + y * this.invX, leftMainInv + x * 18 - 1, y * 18 + 1));
         }
      }

      for(y = 0; y < 9; ++y) {
         this.addSlotToContainer(new Slot(inventoryPlayer, y, y * 18 + leftHotbarInv - 1, 151));
      }

      for(y = 0; y < 3; ++y) {
         for(x = 0; x < 9; ++x) {
            this.addSlotToContainer(new Slot(inventoryPlayer, x + y * 9 + 9, x * 18 + leftHotbarInv - 1, 94 + y * 18 + 1));
         }
      }

   }

   public boolean canInteractWith(EntityPlayer player) {
      return this.tileEntity.isUseableByPlayer(player);
   }

   public ItemStack transferStackInSlot(EntityPlayer player, int islot) {
      int sizeTopInv = this.tileEntity.getSizeInventoryX() * this.tileEntity.getSizeInventoryY();
      ItemStack stackClicked = this.getSlot(islot).getStack();
      if (stackClicked == null) {
         return null;
      } else {
         ItemStack stackCpy = stackClicked.copy();
         if (islot < sizeTopInv) {
            if (!this.mergeItemStack(stackClicked, sizeTopInv, this.inventorySlots.size(), true)) {
               return null;
            }
         } else if (!this.mergeItemStack(stackClicked, 0, sizeTopInv, false)) {
            return null;
         }

         if (stackClicked.stackSize == 0) {
            this.getSlot(islot).putStack((ItemStack)null);
         } else {
            this.getSlot(islot).onSlotChanged();
         }

         return stackCpy;
      }
   }
}
